package com.mingtu.guards.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.hjq.gson.factory.GsonFactory;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.util.XPopupUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.FileParentAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.FileTypeBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;
import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class FileDataActivity extends MyBaseActivity {

    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.iv_plus)
    ImageView ivPlus;
    private boolean isLoadMore = true;
    private FileParentAdapter fileParentAdapter;
    private String addFileTypeName;
    private String typeId;
    private String typeName;
    private boolean isLeader = SPStaticUtils.getBoolean(SPTools.isLeader);
    private List<FileTypeBean.ListBean> DataBean = new ArrayList<>();
    private int currentPosition = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_file_data;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("文件资料");
    }

    @Override
    protected void initData() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new SpacesItemDecoration(0, 0, ItemDecorationSpaces, ItemDecorationSpaces, ItemDecorationSpaces));

        fileParentAdapter = new FileParentAdapter();
        if (isOpenLoadAnimation) {
            fileParentAdapter.isFirstOnly(isFirstOnly);
            fileParentAdapter.openLoadAnimation(animationType);
        }
        fileParentAdapter.setEmptyView(new EmptyDataLayout(context));
        recycler.setAdapter(fileParentAdapter);
        fileParentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //点击文件夹
                FileTypeBean.ListBean listBean = fileParentAdapter.getData().get(position);
                String parentId = listBean.getTypeId();
                String typeName = listBean.getName();
                Bundle bundle = new Bundle();
                bundle.putString("parentId", parentId);
                bundle.putString("typeName", typeName);
                IntentUtils.getInstance().readyGo(ActivityUtil.getTopActivity(), FileSubDataActivity.class, bundle);
            }
        });

        fileParentAdapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
                currentPosition = position;
                //长按文件夹
                fileParentAdapter.updateStatus(position);

                FileTypeBean.ListBean listBean = fileParentAdapter.getData().get(position);
                typeId = listBean.getTypeId();
                typeName = listBean.getName();

                new XPopup.Builder(ActivityUtil.getTopActivity())
                        .moveUpToKeyboard(true) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(new BottomPopup(ActivityUtil.getTopActivity()))
                        .show();
                return false;
            }
        });

        if (!isLeader) {
            ivPlus.setVisibility(View.GONE);
        }
    }

    @Override
    protected void getData() {
        initListener();
        getFileType();
    }

    @OnClick({R.id.iv_plus})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_plus:
                new XPopup.Builder(ActivityUtil.getTopActivity())
                        .moveUpToKeyboard(true) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(new CenterPopup(ActivityUtil.getTopActivity(), 0))
                        .show();
                break;
        }
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setEnableLoadMore(false);
        srlUp.setEnableOverScrollDrag(true);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                getFileType();
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
//                    currentPage = MyUtills.loadPage(DataBean, PAGE_SIZE);
//                    getPictureList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 获取文件类型
     */
    private void getFileType() {
        OkGo.<String>post(MyConstant.POST_FILE_TYPE)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            FileTypeBean fileTypeBean = new FileTypeBean();
                            fileTypeBean = gson.fromJson(result, FileTypeBean.class);
                            List<FileTypeBean.ListBean> dataBeans = fileTypeBean.getList();
                            if (dataBeans != null) {
                                if (dataBeans.size() > 0) {
                                    DataBean.clear();
                                    for (int i = 0; i < dataBeans.size(); i++) {
                                        FileTypeBean.ListBean listBean = dataBeans.get(i);
                                        listBean.setCheck(false);
                                        String parentId = listBean.getParentId();
                                        if (parentId.equals("0")) {
                                            DataBean.add(listBean);
                                        }
                                    }
                                    fileParentAdapter.replaceData(DataBean);
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 新增文件分类
     */
    private void addFileType() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", addFileTypeName);
        hashMap.put("parentId", 0); //已经分类传parentId
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FILE_ADD_TYPE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            addFileTypeName = null;
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                getFileType(); // 刷新文件列表
                            }
                        }
                    }
                });
    }

    /**
     * 修改分类
     */
    private void updateFileType() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", addFileTypeName);
        hashMap.put("typeId", typeId);
        hashMap.put("parentId", 0); //已经分类传parentId
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FILE_UPDATE_TYPE)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("重命名成功！");

                                FileTypeBean.ListBean listBean = new FileTypeBean.ListBean();
                                listBean.setName(addFileTypeName);
                                fileParentAdapter.getData().set(currentPosition,listBean);
                                fileParentAdapter.notifyItemChanged(currentPosition);

                                addFileTypeName = null;

                            }
                        }
                    }
                });
    }

    /**
     * 删除分类
     */
    private void deleteFileType() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("typeId", Integer.parseInt(typeId));
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_FILE_DELETE_TYPE + "/" + typeId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            typeId = null;
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("删除成功！");
                                fileParentAdapter.remove(currentPosition);
                            }
                        }
                    }
                });
    }


    /**
     * 中间弹出的pop
     */
    public class CenterPopup extends CenterPopupView {

        @BindView(R.id.tv_title)
        TextView tvTitle;
        @BindView(R.id.edit_file_name)
        EditText editFileName;
        @BindView(R.id.but_commit)
        Button butCommit;
        int type = 0; // 0：是添加文件夹  1：修改文件夹

        public CenterPopup(@NonNull Context context, int type) {
            super(context);
            this.type = type;
        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.add_file_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            ButterKnife.bind(this);

            if (type == 0) {
                tvTitle.setText("创建文件夹");
            } else if (type == 1) {
                tvTitle.setText("重命名文件夹");
                editFileName.setText(typeName);
                editFileName.setSelection(typeName.length());
            }
            addFileTypeName = typeName;

            editFileName.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                    addFileTypeName = MyUtills.getEditText(editFileName);
                    editFileName.setSelection(addFileTypeName.length());
                }
            });


        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
            KeyboardUtils.hideSoftInput(ActivityUtil.getTopActivity());
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }


        @OnClick({R.id.but_commit})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.but_commit:
                    KeyboardUtils.hideSoftInput(this);
                    if (StringUtils.isEmpty(addFileTypeName)) {
                        ToastUtils.showLong("请输入文件夹名称~");
                        return;
                    }
                    dismiss();
                    if (type == 0) {
                        addFileType();
                    }
                    if (type == 1) {
                        updateFileType();
                    }
                    break;

            }
        }
    }

    /**
     * 底部弹出的pop
     */
    public class BottomPopup extends BottomPopupView {

        @BindView(R.id.tv_rename)
        TextView tvRename;
        @BindView(R.id.tv_delete)
        TextView tvDelete;

        public BottomPopup(@NonNull Context context) {
            super(context);

        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.layout_file_operate;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            ButterKnife.bind(this);
        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
            fileParentAdapter.resetStatus(currentPosition);
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }


        @OnClick({R.id.tv_rename, R.id.tv_delete})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.tv_rename:
                    dismiss();
                    new XPopup.Builder(ActivityUtil.getTopActivity())
                            .moveUpToKeyboard(true) //如果不加这个，评论弹窗会移动到软键盘上面
                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                            .asCustom(new CenterPopup(ActivityUtil.getTopActivity(), 1))
                            .show();
                    break;
                case R.id.tv_delete:
                    dismiss();
                    XPopup.setPrimaryColor(getResources().getColor(com.mingtu.center.R.color.red_fc));
                    new XPopup.Builder(ActivityUtil.getTopActivity())
                            .isDestroyOnDismiss(true)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(true)
                            .asConfirm(context.getResources().getString(R.string.text_tip), "确定要删除文件夹吗？",
                                    context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            deleteFileType();
                                        }
                                    }, null, false)
                            .show();

                    break;
            }
        }
    }

}